package com.spring.lo.framework.factory.xml;

import com.spring.lo.framework.factory.config.BeanDefinition;
import com.spring.lo.framework.factory.support.BeanDefinitionRegistry;
import com.spring.lo.framework.factory.xml.parser.BeanDefinitionParserDelegate;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.List;

/**
 * 简单实现XML读取Document
 * @author zhangbh
 * 2023-05-28 17:18
 **/
public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {

    private final BeanDefinitionRegistry beanDefinitionRegistry;


    public DefaultBeanDefinitionDocumentReader(BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }


    /**
     * 通过Document对象解析BeanDefinition
     * @param document 根元素Bean
     */
    @Override
    public void registerBeanDefinitions(Document document) {
        // 通过预定义的风格读取xml文件，并创建BeanDefinition
        Element rootElement = document.getRootElement();
        BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate();
        if (!delegate.isDefaultNamespace(rootElement)) {
            return;
        }
        List<Element> elements = rootElement.elements();

        for (Element element : elements) {
            BeanDefinition bd = null;
            // 是否是默认命名空间
            if (delegate.isDefaultNamespace(element)) {
                bd = delegate.parseDefaultBeanDefinition(element);
            } else {
                bd = delegate.parseCustomBeanDefinition(element);
            }
            if (bd == null) {
                continue;
            }
            beanDefinitionRegistry.registerBeanDefinition(bd.getBeanName(), bd);
        }
    }


}
